package enterpriseCustomer

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"insighttracking/apps/admin/auth"
	"insighttracking/query/dao"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ModifyEnterpriseCustomerStatusByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewModifyEnterpriseCustomerStatusByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ModifyEnterpriseCustomerStatusByIdApiLogic {
	hostname, _ := os.Hostname()
	return &ModifyEnterpriseCustomerStatusByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ModifyEnterpriseCustomerStatusByIdApiLogic) ModifyEnterpriseCustomerStatusByIdApi(req *types.IdReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	enterpriseCustomerEntity, err := service.EnterpriseCustomerService.GetByIdApi(l.ctx, req.Id)
	if err != nil {
		return "", errors.New("传递的id错误")
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	status := k.If(enterpriseCustomerEntity.Status == 0, 1, 0)
	if err = service.EnterpriseCustomerService.ModifyStatusByIdApi(l.ctx, tx, req.Id, int64(status)); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("修改失败")
	}
	if status == 1 {
		if err = service.AccountService.ModifyStatusByCustomerIdApi(l.ctx, tx, accountInfo.EnterpriseId, req.Id, int64(status+1)); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", err
		}
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("修改失败")
	}
	return "修改成功", nil
}
